var add_collegeList = function (callback1, callback2) {
    var loadDiv = load($(".list"), 99999);
    $("#whatCollege").children("span").text("");
    $("#clasTable").children("tbody").html("");
    $.ajax({
        url: "/college/",
        type: "post",
        data: {
            "token": localStorage['token']
        },
        success: function (data) {
            $("#collegeListTable").children("tbody").html("");
            if (data.code === 200) {
                // console.log(data);
                for (var i = 0; i < data.data.length; i++) {
                    var college = data.data[i];
                    var tr = $('<tr></tr>');
                    addTd(college.id).appendTo(tr);
                    addTd(college.name).appendTo(tr);
                    $(' <td>\n' + ' <button  onclick="addClas($(this))" style="width: 40px;">选取</button>  <button class="redButton" onclick="deleteColelge($(this))"  style="width: 40px;">删除</button>\n' + ' </td>').appendTo(tr);
                    tr.appendTo($("#collegeListTable").children("tbody"));
                }
            } else {
                errorMessage(data.msg);
            }
            if (typeof callback1 === "function") {
                callback1()
            }
            if (callback2 !== "" && typeof callback2 === "function") {
                callback2();
            }
            load_close(loadDiv);
        }
    });

};

var tableChange = function (tableSelector) {
    var ths = $(tableSelector).children("thead").children("tr").children("th");

    var tds = $(tableSelector).children("tbody").children("tr").first().children("td");
    var td = tds.first();
    for (var i = 0; i < ths.length; i++) {
        var thWidht = ths[i].getBoundingClientRect().width;
        td.innerWidth(thWidht);
        td = tds.next();
    }

};

var addClas = function (btn) {
    var collegeId = btn.parent().parent().children("td").first().text();
    var collegeName = btn.parent().parent().children("td").first().next().text();
    $("#whatCollege").children("span").text("");
    $("#whatCollege").children("span").text(collegeName);
    addGrade($("#clasTable").children("tbody"), function () {
        tableChange("#clasTable")
    });

    var loadDiv = load("#clasTableDiv", 9999);
    $.ajax({
            url: "/clas",
            type: "post",
            data: {
                "token": localStorage['token'],
                "collegeId": collegeId
            },
            success: function (data) {
                message("获取班级成功!", "", "success", 1500);
                // console.log(data);
                if (data.code === 200) {
                    console.log(data);
                    var trs = $("#clasTable").children("tbody").children("tr");
                    var tr = trs.first();
                    // console.log(tr);
                    for (var i = 0; i < 8; i++) {
                        var grade = tr.children("td").first().text();
                        // console.log(grade);
                        var subTr = $("<tr style='display: none'></tr>");
                        var subTd = $(" <td class='subTable' colspan='3' style='padding:0!important;'></td>");
                        var subDiv = $('<div class="subTable" >');
                        var subTable = $(" <table></table>");
                        var subTbody = $('<tbody></tbody>');
                        subTable.appendTo(subDiv);
                        subDiv.appendTo(subTd);
                        subTd.appendTo(subTr);
                        for (var j = 0; j < data.data.length; j++) {
                            var college = data.data[j];
                            // console.log(college);
                            if (college.clasGrade === grade) {
                                console.log(college);
                                var clas = data.data[j].clas;
                                for (var k = 0; k < data.data[j].clas.length; k++) {
                                    var childrTr = $("<tr></tr>");
                                    addTdHidId(clas[k].id).appendTo(childrTr );
                                    // console.log(college);
                                    addTd(college.clasGrade + college.collegeId + clas[k].clasNum).appendTo(childrTr);
                                    var td = $('<td></td>');
                                    $('<button class="redButton" onclick="detailClas($(this))">查看</button>').appendTo(td);
                                    $('<button class="redButton" onclick="deleteClas($(this))">删除</button>').appendTo(td);
                                    td.appendTo(childrTr);
                                    childrTr.appendTo(subTbody);
                                    subTbody.appendTo(subTable);
                                }
                                subTr.insertAfter(tr);
                            }
                        }
                        tr = tr.next();
                    }
                } else {
                    message(data.msg, "请尝试尝试或者联系管理员", "error", 1500);
                }
                load_close(loadDiv);
            }
        }
    )
};

var addGrade = function (seletor, callBack) {
    seletor.html("");
    var gradeTable = $('<tr onclick="showSubTable($(this).next())" style="cursor: pointer">\n' +
        '                    <td>18</td>\n' +
        '                    <td></td>\n' +
        '                    <td><button>点击展开</button></td>\n' +
        '                </tr>\n' +
        '                <tr onclick="showSubTable($(this).next())" style="cursor: pointer">\n' +
        '                    <td>17</td>\n' +
        '                    <td></td>\n' +
        '                    <td><button>点击展开</button></td>\n' +
        '                </tr>\n' +
        '                <tr onclick="showSubTable($(this).next())" style="cursor: pointer">\n' +
        '                    <td>16</td>\n' +
        '                    <td></td>\n' +
        '                    <td><button>点击展开</button></td>\n' +
        '                </tr>\n' +
        '                <tr onclick="showSubTable($(this).next())" style="cursor: pointer">\n' +
        '                    <td>15</td>\n' +
        '                    <td></td>\n' +
        '                    <td><button>点击展开</button></td>\n' +
        '                </tr>');
    gradeTable.appendTo(seletor);
    if (callBack !== "" && typeof callBack === "function") {
        callBack();
    }
};


$("#saveCollegeBtn").click(function () {
    var loadDiv = load("#saveCollegeDialog", 99999);
    $.ajax({
        url: "/college/save",
        type: "post",
        data: {
            "token": localStorage['token'],
            "id": $("#cid").val(),
            "name": $("#cname").val()
        },
        success: function (data) {
            if (data.code === 200) {
                message("保存成功!", "", "success", 1500);
                // console.log(data);
                dialog_close();
                add_collegeList(function () {
                    tableChange("#collegeListTable")
                }, "");
            } else {
                message(data.msg, "请尝试尝试或者联系管理员", "error", 1500);
            }
            load_close(loadDiv);
        }
    })
});
var showSubTable = function (tr) {
    tr.stop().fadeToggle();
    event.stopPropagation();
};

$("#saveCollege").click(function () {
    dialog_show();
    $(".dialog").load("page/admin/collegeSave");
});


$("#cid").blur(function () {
    var test = /^[\d]{2}$/;
    if (!test.test($(this).val())) {
        $(this).parent().children(".errorMsg").text("序号为两位数字!");
    } else {
        $(this).parent().children(".errorMsg").empty();
    }

    setTimeout(function () {
        testSaveCollege()
    }, 10);
});

$("#cname").blur(function () {
    var test = /^[\u4E00-\u9FA5]+$/;
    if (!test.test($(this).val())) {
        $(this).parent().children(".errorMsg").text("名称必须为中文!");
    } else {
        $(this).parent().children(".errorMsg").empty();
    }
    setTimeout(function () {
        testSaveCollege()
    }, 10);
});

var testSaveCollege = function () {
    var flag = true;
    $("#saveCollegeDialog").children(".content").children(".SHinput").each(function () {
        flag = flag && $(this).hasClass("input_success");
    });
    if (flag == false) {
        $("#saveCollegeBtn").attr("disabled", "disabled");
        $("#saveCollegeBtn").addClass("button_cannot");
    } else {
        $("#saveCollegeBtn").removeAttr("disabled");
        $("#saveCollegeBtn").removeClass("button_cannot");
    }
};


$("#saveClas").click(function () {
    dialog_show();
    $(".dialog").load("page/admin/clasSave");
    addCollege();
});

$("#clasNum").blur(function () {
    var test = /^[\d]{2}$/;
    if (!test.test($(this).val())) {
        $(this).parent().children(".errorMsg").text("班号为两位数字!");
    } else {
        $(this).parent().children(".errorMsg").empty();
    }

    setTimeout(function () {
        testSaveClas();
    }, 10);


});

var testSaveClas = function () {
    var college = $("#college").next().val();
    var grade = $("#clasGrade").next().val();
    // console.log(grade);
    var flag = $("#clasNum").parent().hasClass("input_success") && !(isNull(college))
        && !(isNull(grade));
    // console.log(flag);
    if (!flag) {
        $("#clasSaveBtn").attr("disabled", "disabled");
        $("#clasSaveBtn").addClass("button_cannot");
    } else {
        $("#clasSaveBtn").removeAttr("disabled");
        $("#clasSaveBtn").removeClass("button_cannot");
    }
};
$("#clasSaveBtn").click(function () {
    var loadDiv = load("#saveClasDialog", 99999);
    $.ajax({
        url: "clas/save",
        type: "post",
        data: {
            "token": localStorage['token'],
            "clasGrade": $("#clasGrade").next().val(),
            "collegeId": $("#college").next().val(),
            "clasNum": $("#clasNum").val()
        },
        success: function (data) {
            if (data.code === 200) {
                message("新增班级成功", "", "success", 1500);
                dialog_close();
            } else {
                errorMessage(data.msg);
            }
            load_close(loadDiv);

        }
    })
});
var addCollege = function () {
    $.ajax(
        {
            url: "college",
            type: "post",
            data: {
                "token": localStorage['token']
            },
            success: function (data) {
                $("#college").next().next().next().children("ul").text("");
                if (data.code === 200) {
                    for (var i = 0; i < data.data.length; i++) {
                        var college = data.data[i];
                        var li = addOption(college.name, college.id);
                        li.appendTo($("#college").next().next().next().children("ul"));

                    }
                } else {
                    message(data.msg, "请尝试尝试或者联系管理员", "error", 1500);
                }
            }
        }
    )
};
var detailClas = function (btn) {
    var id = btn.parent().parent().children("td").first().text();
    var loadDiv = load("#body", 99999);
    var url = "/page/admin/studentList";
    $("#body").load(url);
    console.log(id);
    setTimeout(function () {
        addData_studentList(10, 1, "", "", id, "");
        load_close(loadDiv);
    },500);
};

var deleteColelge = function (btn) {
    swal(
        {
            title: "您确定要删除这条数据吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            buttons: ["取消", "确定删除！"],
            dangerMode: true
        }
    ).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: "/college/remove",
                type: "post",
                data: {
                    "token": localStorage['token'],
                    "id": btn.parent().parent().children("td").first().text()
                },
                success: function (data) {
                    if (data.code === 200) {
                        message("删除成功!", "", "success", 1500);
                    } else {
                        message(data.msg, "请尝试尝试或者联系管理员", "error", 1500);
                    }
                    add_collegeList(function () {
                        tableChange("#collegeListTable")
                    }, "");
                }
            })
        } else {
            swal("取消成功"
            )
            ;
        }
    })
    ;


};


var deleteClas = function (btn) {
    var loadDiv = load("collegeListTable", 999999);
    var clas = btn.parent().parent().children("td").first().next().text();
    var clasGrade = clas.substr(0, 2);
    var collegeId = clas.substr(2, 2);
    var clasNum = clas.substr(4, 2);
    swal(
        {
            title: "您确定要删除这条数据吗",
            text: "删除后将无法恢复，请谨慎操作！",
            type: "warning",
            buttons: ["取消", "确定删除！"],
            dangerMode: true
        }
    ).then((willDelete) => {
        if (willDelete) {
            $.ajax({
                url: "/clas/remove",
                type: "post",
                data: {
                    "token": localStorage['token'],
                    "clasGrade": clasGrade,
                    "clasNum": clasNum,
                    "collegeId": collegeId
                },
                success: function (data) {
                    if (data.code === 200) {
                        message("删除成功!", "", "success", 1500);
                    } else {
                        message(data.msg, "请尝试尝试或者联系管理员", "error", 1500);
                    }
                    add_collegeList(function () {
                        tableChange("#collegeListTable")
                    }, "");
                }
            })
        } else {
            swal("取消成功"
            )
            ;
        }
    })
    ;


}